<?php
abstract class Pageley_Gateway_Database_Condition_AbstractSqlDecorator implements Pageley_Gateway_Database_Condition_SqlDecorator {
	
	private $decoratedCondition;
	private $sql;
	
	public function __construct($decoratedCondition) {
		$this->decoratedCondition = $decoratedCondition;
	}
	
	public function setQuery($query) {
		$this->decoratedCondition->setQuery($query);
	}
	
	public function matches($entity) {
		return $this->decoratedCondition->matches($entity);
	}
	
	public function getValues() {
		return $this->decoratedCondition->getValues();
	}
	
	public function getOperator() {
	    return Pageley_Util_String::toUpperCase($this->getDecoratedCondition()->getOperator());
	}
	
	protected function getDecoratedCondition() {
		return $this->decoratedCondition;
	}
	
	protected abstract function createSql();
	
	public function toSql() {
		if($this->sql === null) {
			$this->sql = $this->createSql();
		}
		return $this->sql;
	}
	
	public static function decorateCondition($condition, $query) {
		$decoratedCondition = null;
		if($condition instanceof Pageley_Query_Condition_Aggregate) {
			$decoratedCondition = new Pageley_Gateway_Database_Condition_AggregateSqlDecorator($condition, $query);
		} else if($condition instanceof Pageley_Query_Condition_Equals) {
			$decoratedCondition = new Pageley_Gateway_Database_Condition_EqualsSqlDecorator($condition, $query);
		} else if($condition instanceof Pageley_Query_Condition_Contains) {
            $decoratedCondition = new Pageley_Gateway_Database_Condition_ContainsSqlDecorator($condition, $query);
        } else if($condition instanceof Pageley_Query_Condition_Single) {
			$decoratedCondition = new Pageley_Gateway_Database_Condition_SingleSqlDecorator($condition, $query);
		} else if($condition instanceof Pageley_Query_Condition_Not) {
			$decoratedCondition = new Pageley_Gateway_Database_Condition_NotSqlDecorator($condition, $query);
		} else {
			throw new Pageley_Gateway_Exception("Unsupported condition type '"
				. get_class($condition) . "'.");
		}
		return $decoratedCondition;
	}
}